package com.xuetang.service.impl;

import com.xuetang.entity.SysUser;
import com.xuetang.mapper.SysUserMapper;
import com.xuetang.security.JwtTokenUtil;
import com.xuetang.security.LoginUser;
import com.xuetang.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${xuetang.wx.appid}")
    private String appId;

    @Value("${xuetang.wx.secret}")
    private String appSecret;

    @Value("${xuetang.wx.login-url}")
    private String wxLoginUrl;

    @Override
    public SysUser getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public SysUser getUserByOpenid(String openid) {
        return userMapper.selectByOpenid(openid);
    }

    @Override
    public Map<String, Object> wxLogin(String code, Map<String, Object> userInfo) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 打印接收到的用户信息
            System.out.println("接收到的用户信息: " + userInfo);

            // 调用微信接口获取openid和session_key
            String url = String.format(wxLoginUrl, appId, appSecret, code);
            System.out.println("微信登录URL: " + url);

            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            Map<String, Object> wxResult = response.getBody();
            System.out.println("微信接口返回: " + wxResult);

            if (wxResult.containsKey("errcode")) {
                // 微信接口返回错误
                result.put("success", false);
                result.put("message", "微信登录失败: " + wxResult.get("errmsg"));
                return result;
            }

            String openid = (String) wxResult.get("openid");
            String sessionKey = (String) wxResult.get("session_key");
            System.out.println("获取到openid: " + openid);

            // 根据openid查询用户
            SysUser user = getUserByOpenid(openid);
            boolean isNewUser = false;

            if (user == null) {
                // 用户不存在，自动注册
                System.out.println("用户不存在，创建新用户");
                isNewUser = true;
                user = new SysUser();
                user.setOpenid(openid);

                // 使用微信用户信息
                if (userInfo != null && !userInfo.isEmpty()) {
                    // 直接打印每个字段，确保能够获取到
                    System.out.println("nickName: " + userInfo.get("nickName"));
                    System.out.println("avatarUrl: " + userInfo.get("avatarUrl"));
                    System.out.println("gender: " + userInfo.get("gender"));

                    // 获取用户信息，注意字段名称
                    String nickName = (String) userInfo.get("nickName");
                    String avatarUrl = (String) userInfo.get("avatarUrl");
                    Integer gender = userInfo.get("gender") != null
                            ? Integer.parseInt(userInfo.get("gender").toString())
                            : 0;

                    // 生成唯一用户名，避免冲突
                    String username = "wx_" + openid.substring(0, 8);
                    int suffix = 1;
                    while (getUserByUsername(username) != null) {
                        username = "wx_" + openid.substring(0, 8) + "_" + suffix;
                        suffix++;
                    }

                    user.setUsername(username);
                    user.setNickname(
                            nickName != null && !nickName.isEmpty() ? nickName : "用户" + openid.substring(0, 4));
                    user.setAvatar(avatarUrl);
                    user.setGender(gender);

                    System.out.println("设置用户信息 - username: " + user.getUsername() + ", nickname: " + user.getNickname()
                            + ", avatar: " + user.getAvatar());

                    // 设置其他信息
                    String country = (String) userInfo.get("country");
                    String province = (String) userInfo.get("province");
                    String city = (String) userInfo.get("city");

                    System.out.println("其他信息 - country: " + country + ", province: " + province + ", city: " + city);
                } else {
                    user.setUsername("wx_" + openid.substring(0, 8));
                    user.setNickname("用户" + openid.substring(0, 4)); // 生成昵称
                    System.out.println("未获取到用户信息，使用默认值");
                }

                user.setPassword(""); // 微信用户不需要密码
                user.setStatus(1); // 正常状态
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                user.setLastLoginTime(LocalDateTime.now());

                // 保存用户
                save(user);
                System.out.println("新用户已创建: " + user.getId());
            } else {
                // 更新用户信息
                System.out.println("用户已存在，更新信息");
                boolean needUpdate = false;

                // 如果有新的用户信息，则更新
                if (userInfo != null && !userInfo.isEmpty()) {
                    // 直接打印每个字段，确保能够获取到
                    System.out.println("nickName: " + userInfo.get("nickName"));
                    System.out.println("avatarUrl: " + userInfo.get("avatarUrl"));
                    System.out.println("gender: " + userInfo.get("gender"));

                    String nickName = (String) userInfo.get("nickName");
                    String avatarUrl = (String) userInfo.get("avatarUrl");
                    Integer gender = userInfo.get("gender") != null
                            ? Integer.parseInt(userInfo.get("gender").toString())
                            : null;

                    if (nickName != null && !nickName.isEmpty() && !nickName.equals(user.getNickname())) {
                        user.setNickname(nickName);
                        needUpdate = true;
                        System.out.println("更新昵称: " + nickName);
                    }

                    if (avatarUrl != null && !avatarUrl.isEmpty() && !avatarUrl.equals(user.getAvatar())) {
                        user.setAvatar(avatarUrl);
                        needUpdate = true;
                        System.out.println("更新头像: " + avatarUrl);
                    }

                    if (gender != null && !gender.equals(user.getGender())) {
                        user.setGender(gender);
                        needUpdate = true;
                        System.out.println("更新性别: " + gender);
                    }
                }

                // 更新登录时间
                user.setLastLoginTime(LocalDateTime.now());
                needUpdate = true;

                if (needUpdate) {
                    updateById(user);
                    System.out.println("用户信息已更新");
                }
            }

            // 生成token
            String token = jwtTokenUtil.generateToken(user.getUsername());
            System.out.println("生成token: " + token);

            // 组装返回结果
            result.put("success", true);
            result.put("token", token);
            result.put("isNewUser", isNewUser);

            Map<String, Object> userInfoMap = new HashMap<>();
            userInfoMap.put("id", user.getId());
            userInfoMap.put("username", user.getUsername());
            userInfoMap.put("nickname", user.getNickname());
            userInfoMap.put("avatar", user.getAvatar());
            userInfoMap.put("gender", user.getGender());
            userInfoMap.put("diabetesType", user.getDiabetesType());

            result.put("userInfo", userInfoMap);
            System.out.println("返回用户信息: " + userInfoMap);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "微信登录异常: " + e.getMessage());
        }

        return result;
    }

    @Override
    public String login(String username, String password) {
        // 简单实现，实际应该加密比较密码
        SysUser user = getUserByUsername(username);
        if (user != null && password.equals(user.getPassword())) {
            return jwtTokenUtil.generateToken(username);
        }
        return null;
    }

    @Override
    public boolean register(SysUser user) {
        // 检查用户名是否已存在
        SysUser existUser = getUserByUsername(user.getUsername());
        if (existUser != null) {
            return false;
        }

        // 设置创建时间等信息
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1); // 正常状态

        return save(user);
    }

    @Override
    public boolean updateUserInfo(SysUser user) {
        // 只更新允许的字段
        SysUser updateUser = new SysUser();
        updateUser.setId(user.getId());
        updateUser.setNickname(user.getNickname());
        updateUser.setAvatar(user.getAvatar());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setGender(user.getGender());
        updateUser.setAge(user.getAge());
        updateUser.setHeight(user.getHeight());
        updateUser.setWeight(user.getWeight());
        updateUser.setDiabetesType(user.getDiabetesType());
        updateUser.setDiagnosisDate(user.getDiagnosisDate());
        updateUser.setUpdateTime(LocalDateTime.now());

        return updateById(updateUser);
    }

    @Override
    public LoginUser getCurrentUser() {
        // 简化实现，不再依赖SecurityContextHolder
        // 在实际项目中，需要根据具体的认证方式获取当前用户
        return null;
    }

    @Override
    public boolean save(SysUser user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public SysUser getById(Long id) {
        return userMapper.selectById(id);
    }

    private boolean updateById(SysUser user) {
        return userMapper.updateById(user) > 0;
    }
}